package lib
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextLineMetrics;
	
	import mx.controls.Alert;
	import mx.controls.ComboBox;
	
	public class DropDownList extends ComboBox
	{
		private const  PADDING:int = 30;
		private var _valueField:String;
		private var _selectedValue:Object;
		
		public function DropDownList()
		{
			super();
		}
		
		/*
		 * if set to true the system will resize the combo box dropdown 
		 * when mouse move over the combo box
		 */
		public function set monitorDropdownWidth(value:Boolean):void
		{
			if (value == true || !this.hasEventListener(MouseEvent.MOUSE_OVER) )
			{
				this.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
			}
			else
			{
				this.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
			}
		}
		
		/*
		 * property valueField: id field of the combo box item  
		 */
		public function set valueField(value:String):void
		{
			_valueField = value;
		}
		
		public function get valueField():String
		{
			return _valueField;
		}
		
		/*
		 * property selectedValue: get or set the selected value field (id field)
		 * user can pre set selectValue then later assign dataprovider and component will
		 * select the appropriate index after dataprovider is set.
		 */
		public function get selectedValue():Object
		{
			if (_valueField == null || dataProvider == null)
				return null;
			
			return super.selectedItem[_valueField];
		}
		
		public function set selectedValue(value:Object):void
		{
			_selectedValue = value;
			selectValue();
		}
		
		/*
		 * set the combo box dropdown with
		 * if monitorDropdownWidth = true, the width is recalculate 
		 * everytime mouse is moved over combo box 
		 */
		public function setDropDownWidth():void
		{
			super.dropdownWidth = width;
			for (var i:int=0; i< dataProvider.length; i++)
			{
				var o:Object = dataProvider[i];
				var tlm:TextLineMetrics = measureText( itemToLabel(o) );
				if (super.dropdownWidth < tlm.width + PADDING)
	    		{
	    			super.dropdownWidth = tlm.width + PADDING;
	    		}
			}
		}
		
		public override function set dataProvider(value:Object):void
		{
			super.dataProvider = value;
			selectValue();
			setDropDownWidth();
		}
				
		private function selectValue():void
		{
			if (_valueField == null || dataProvider == null || dataProvider.length == 0)
				return;
				
			for (var i:int=0; i<dataProvider.length; i++)
			{
				var obj:Object = dataProvider[i];
				if (obj[_valueField] == _selectedValue)
				{
					super.selectedIndex = i;
					return;
				}	
			}
		}
		
		private function mouseOverHandler(event:Event):void
		{
			setDropDownWidth();
		}
	}
}